package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcPrepaidCycleMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcPaymentCycle;
import com.csun.cmny.provider.model.domain.OmcPrepaidCycle;
import com.csun.cmny.provider.model.domain.OmcReturnFeeConfig;
import com.csun.cmny.provider.model.dto.PrepaidCycleDto;
import com.csun.cmny.provider.service.OmcPrepaidCycleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
@Transactional
public class OmcPrepaidCycleServiceImpl extends BaseService<OmcPrepaidCycle> implements OmcPrepaidCycleService {

    @Resource
    private OmcPrepaidCycleMapper omcPrepaidCycleMapper;

    @Override
    public Integer savePrepaidCycle(OmcPrepaidCycle omcPrepaidCycle, LoginAuthDto loginAuthDto) {

        omcPrepaidCycle.setUpdateInfo(loginAuthDto);
        omcPrepaidCycle.setGroupId(omcPrepaidCycle.getGroupId());
        checkRepeat(omcPrepaidCycle);

        return omcPrepaidCycleMapper.insertSelective(omcPrepaidCycle);
    }

    @Override
    public List<OmcPrepaidCycle> queryPrepaidCycle(PrepaidCycleDto prepaidCycleDto, LoginAuthDto loginAuthDto) {

        OmcPrepaidCycle query = new OmcPrepaidCycle();

        //如果未传入机构id,查询操作者机构的数据
        if(prepaidCycleDto.getGroupId() != null){
            query.setGroupId(prepaidCycleDto.getGroupId());
        }else{
            query.setGroupId(loginAuthDto.getGroupId());
        }
        return select(query);
    }

    public void checkRepeat(OmcPrepaidCycle omcPrepaidCycle){
        Example example = new Example(OmcPrepaidCycle.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("groupId",omcPrepaidCycle.getGroupId());
        criteria.andEqualTo("isAddSurplusDays",omcPrepaidCycle.getIsAddSurplusDays());
        criteria.andEqualTo("prepaidMonthNum",omcPrepaidCycle.getPrepaidMonthNum());
        if(selectCountByExample(example) > 0){
            throw new OmcBizException(ErrorCodeEnum.OMC10037012);
        }
    }
}
